package com.ddwl.wallet.service;

import cn.hutool.core.util.RandomUtil;
import com.ddwl.common.constant.RedisKey;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.service.RedisService;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.wallet.DeductedSubsidyBo;
import com.ddwl.schema.bo.wallet.ProvideSubsidyBo;
import com.ddwl.schema.bo.wallet.UserSubsidyFlowQueryBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.wallet.UserSubsidyFlowVo;
import com.ddwl.schema.vo.wallet.UserSubsidyVo;
import com.ddwl.wallet.dao.SubsidyDao;
import com.ddwl.wallet.dao.UserSubsidyDao;
import com.ddwl.wallet.dao.UserSubsidyFlowDao;
import com.ddwl.wallet.dao.model.Subsidy;
import com.ddwl.wallet.dao.model.UserSubsidy;
import com.ddwl.wallet.dao.model.UserSubsidyFlow;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * 类UserCouponService.java的实现描述：用户优惠券
 *
 * @author zach
 * @Date :2020-07-29 14:56.
 */
@Service
public class UserSubsidyService {

    /**
     * 津贴Id
     */
    private String subsidyId = "1595509965738877952";

    @Resource
    private RedisService redisService;
    @Resource
    private UserSubsidyDao userSubsidyDao;
    @Resource
    private SubsidyDao subsidyDao;
    @Resource
    private UserSubsidyFlowDao userSubsidyFlowDao;


    /**
     * 查询津贴流水
     * @param bo
     * @return
     */
    public PageVo<UserSubsidyFlowVo> queryPage(PageBo<UserSubsidyFlowQueryBo> bo){
        PageHelper.startPage(bo.getPage(),bo.getPageSize(), MySqlUtil.orderBy(bo.getSort(),bo.isAsc()));
        PageInfo<UserSubsidyFlow> info = new PageInfo(userSubsidyFlowDao.querySubsidyFlow(bo.getParam()));
        return new PageVo<>(info.getTotal(),bo.getPage(),bo.getPageSize(),BeanConverUtils.convertBeanList(info.getList(),UserSubsidyFlowVo.class));
    }



    /**
     * 获取购物津贴
     * @param dk
     * @return
     */
    public BigDecimal createCoupon(String dk){
        String key = RedisKey.COUPON_NEW_KEY.getKey(dk);
        if(redisService.getValueOps().getOperations().hasKey(key)){
            return new BigDecimal(redisService.getValueOps().get(key));
        }
        Subsidy userSubsidy = subsidyDao.selectByPrimaryKey(subsidyId);
        BigDecimal bigDecimal = BigDecimal.valueOf(RandomUtil.randomInt(userSubsidy.getIntervalMin(),userSubsidy.getIntervalMax())*(userSubsidy.getIntervalUnit()));
        redisService.getValueOps().set(key, bigDecimal.toString());
        redisService.getValueOps().getOperations().expire(key, 1, TimeUnit.DAYS);
        return bigDecimal;
    }

    /**
     * 用户领取优惠券
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal take(String userId){
        UserSubsidyFlow flow = userSubsidyFlowDao.getSubsidyFlowBySubsidyId(subsidyId,userId);
        ParamException.isNotNull(flow,"该用户已经领取过购物津贴了");
        Subsidy subsidy = subsidyDao.selectByPrimaryKey(subsidyId);
        BigDecimal bigDecimal = BigDecimal.valueOf(RandomUtil.randomInt(subsidy.getIntervalMin(),subsidy.getIntervalMax())*(subsidy.getIntervalUnit()));
        UserSubsidy userSubsidy = userSubsidyDao.getCouponByCouponId(userId);
        userSubsidy.setAmount(userSubsidy.getAmount().add(bigDecimal));
        userSubsidyDao.updateByPrimaryKeySelective(userSubsidy);
        UserSubsidyFlow flow1 = new UserSubsidyFlow();
        flow1.setFlowId(subsidyId);
        flow1.setAmount(bigDecimal);
        flow1.setType(1);
        flow1.setMsg("新人购物津贴");
        flow1.setUserId(userId);
        userSubsidyFlowDao.insert(flow1);
        return bigDecimal;
    }

    /**
     * 订单抵扣用户购物津贴
     * @param bo
     */
    @Transactional(rollbackFor = Exception.class)
    public void deductedSubsidy(DeductedSubsidyBo bo){
        UserSubsidy userSubsidy = userSubsidyDao.getCouponByCouponId(bo.getUserId());
        ParamException.isTrue(bo.getAmount().compareTo(userSubsidy.getAmount())>0,"账户余额不足");
        userSubsidy.setAmount(userSubsidy.getAmount().subtract(bo.getAmount()));
        userSubsidyDao.updateByPrimaryKeySelective(userSubsidy);
        UserSubsidyFlow flow1 = new UserSubsidyFlow();
        flow1.setFlowId(bo.getOrderId());
        flow1.setAmount(bo.getAmount());
        flow1.setType(0);
        flow1.setMsg("订单抵扣");
        flow1.setUserId(bo.getUserId());
        userSubsidyFlowDao.insert(flow1);
    }


    public boolean isTake(String userId){
        return userSubsidyFlowDao.getSubsidyFlowBySubsidyId(subsidyId,userId) != null;
    }

    /**
     * 查询用户购物津贴
     * @return
     */
    public UserSubsidyVo getUserCouponVo(String userId,String product){
        return BeanConverUtils.convertBean(userSubsidyDao.getCouponByCouponId(userId),UserSubsidyVo.class);
    }

    public UserSubsidyVo getUserCouponVo(String userId){
        return BeanConverUtils.convertBean(userSubsidyDao.getCouponByCouponId(userId),UserSubsidyVo.class);
    }

    /**
     * 发放津贴
     * @param bo
     */
    @Transactional(rollbackFor = Throwable.class)
    @Async
    public void provideSubsidy(ProvideSubsidyBo bo) {
        UserSubsidy userSubsidy = userSubsidyDao.getCouponByCouponId(bo.getUserId());
        userSubsidy.setAmount(userSubsidy.getAmount().add(bo.getRewardSubsidy()));
        userSubsidyDao.updateByPrimaryKeySelective(userSubsidy);
        UserSubsidyFlow flow1 = new UserSubsidyFlow();
        flow1.setFlowId(bo.getFlowId());
        flow1.setAmount(bo.getRewardSubsidy());
        flow1.setType(bo.getType());
        flow1.setMsg(bo.getMsg());
        flow1.setUserId(bo.getUserId());
        userSubsidyFlowDao.insert(flow1);
    }
}
